import 'dart:convert';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:gift_listing/common/utils.dart';
import 'package:gift_listing/components/form_text.dart';
import 'package:gift_listing/components/gift_datepicker.dart';
import 'package:gift_listing/components/toast.dart';
import 'package:gift_listing/global.dart';
import 'package:gift_listing/manager/gift_manager.dart';
import 'package:gift_listing/manager/notification_manager.dart';
import 'package:provider/provider.dart';

class GiftEditPage extends StatefulWidget {
  GiftEditPage({Key key}) : super(key: key);
  @override
  State<StatefulWidget> createState() => _GiftEditPageState();
}

class _GiftEditPageState extends State<GiftEditPage> {
  Widget buildGiftList(data) {
    var _data = data is String ? json.decode(data) : data;

    List<Widget> _children = [];
    List.generate(_data.length, (index) {
      final gift = _data[index];
      _children.add(Row(
        children: [
          Expanded(
            flex: 2,
            child: FormText(
              maxLine: 1,
              text: gift['gift_name'],
              hintText: '礼品名称',
              onChanged: (text) {
                gift['gift_name'] = text;
              },
            ),
          ),
          SizedBox(width: 10),
          Expanded(
            flex: 1,
            child: FormText(
              maxLine: 1,
              text: gift['recipient'],
              hintText: '收礼人',
              onChanged: (text) {
                gift['recipient'] = text;
              },
            ),
          ),
          SizedBox(width: 10),
          IconButton(
            icon: Icon(Icons.delete),
            tooltip: '删除清单项',
            onPressed: () {
              Utils.showConfirmDialog(
                context: context,
                content: '确认删除该项？',
                confirmCallback: () {
                  setState(() => {data.removeAt(index)});
                },
                showCancelButton: true,
              );
            },
          )
        ],
      ));
    });
    return Column(children: _children);
  }

  bool _lights;

  @override
  Widget build(BuildContext context) {
    NotificationManager _notificationManager =
        Provider.of<NotificationManager>(context);
    GiftManager _giftManager = Provider.of<GiftManager>(context);

    setState(() {
      _lights = _lights == null
          ? (_giftManager.currentGift['notification'] == 1 ? true : false)
          : _lights;
    });

    return Scaffold(
      appBar: AppBar(
        elevation: 0,
        actions: <Widget>[
          Offstage(
            offstage: false,
            child: IconButton(
              icon: Icon(Icons.save),
              tooltip: '保存',
              onPressed: () async {
                if (_giftManager.currentGift['title'] == '') {
                  Toast.show(context, msg: '您还没有填写标题');
                  return;
                }
                if (_giftManager.currentGift['startDate'] == '开始日期') {
                  Toast.show(context, msg: '请选择开始日期');
                  return;
                }
                if (_giftManager.currentGift['endDate'] == '结束日期') {
                  Toast.show(context, msg: '请选择结束日期');
                  return;
                }
                if (_giftManager.currentGift['gifts'].length == 0) {
                  Toast.show(context, msg: '请至少添加一项礼品');
                  return;
                }

                if (_giftManager.currentGift['id'] != null) {
                  // 修改的清单
                  if (!(_giftManager.currentGift['notification'] == 1 ||
                      _giftManager.currentGift['notification'])) {
                    // 不允许通知 取消已注册的通知
                    _notificationManager
                        .cancelNotification(_giftManager.currentGift['id']);
                  }
                  _giftManager.update(
                    id: _giftManager.currentGift['id'],
                    title: _giftManager.currentGift['title'],
                    startDate: _giftManager.currentGift['startDate'],
                    endDate: _giftManager.currentGift['endDate'],
                    notification: _giftManager.currentGift['notification'] == 1,
                    remark: _giftManager.currentGift['remark'],
                    gifts: jsonEncode(_giftManager.currentGift['gifts']),
                  );
                } else {
                  // 新添加的清单
                  if (_giftManager.currentGift['notification'] == 1 ||
                      _giftManager.currentGift['notification']) {
                    final date =
                        DateTime.parse(_giftManager.currentGift['startDate']);
                    final prevDate = date.subtract(new Duration(days: 1));
                    await _notificationManager.registeredFutureNotification(
                      id: _giftManager.allGift.length,
                      title: '',
                      content: '',
                      payload: '',
                      time: DateTime(
                          prevDate.year, prevDate.month, prevDate.day, 18, 00),
                    );
                  }

                  _giftManager.insert(
                    id: _giftManager.allGift.length,
                    title: _giftManager.currentGift['title'],
                    startDate: _giftManager.currentGift['startDate'],
                    endDate: _giftManager.currentGift['endDate'],
                    notification: _giftManager.currentGift['notification'] == 1,
                    remark: _giftManager.currentGift['remark'],
                    gifts: jsonEncode(_giftManager.currentGift['gifts']),
                  );
                }
                Toast.show(context, msg: '清单保存成功');
                Navigator.pop(context);
              },
            ),
          )
        ],
        title: Text(
          '${_giftManager.currentGift['id'] == null ? "新建" : "编辑"}礼品清单',
          style: TextStyle(
            color: Global.fontColor,
            fontSize: 15,
          ),
          maxLines: 1,
          overflow: TextOverflow.ellipsis,
        ),
      ),
      body: Container(
        padding: EdgeInsets.all(10),
        width: MediaQuery.of(context).size.width,
        height: MediaQuery.of(context).size.height,
        decoration: BoxDecoration(color: Global.backgroundColor),
        child: SingleChildScrollView(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            mainAxisAlignment: MainAxisAlignment.start,
            children: <Widget>[
              formTitle(title: '清单信息'),
              SizedBox(height: 10),
              FormText(
                maxLine: 1,
                text: _giftManager.currentGift['title'],
                hintText: '标题（如：中秋节礼品）',
                onChanged: (text) {
                  _giftManager.currentGift['title'] = text;
                },
              ),
              SizedBox(height: 15),
              Row(
                children: [
                  Expanded(
                    child: GiftDatepicker(
                      initDate: _giftManager.currentGift['startDate'],
                      onChange: (date) {
                        _giftManager.currentGift['startDate'] = date;
                      },
                    ),
                  ),
                  SizedBox(width: 10),
                  Expanded(
                    child: GiftDatepicker(
                      initDate: _giftManager.currentGift['endDate'],
                      onChange: (date) {
                        _giftManager.currentGift['endDate'] = date;
                      },
                    ),
                  ),
                ],
              ),
              SizedBox(height: 15),
              Container(
                padding: EdgeInsets.fromLTRB(10, 3, 15, 3),
                decoration: BoxDecoration(
                  color: Global.fontSecondColor.withOpacity(0.08),
                  borderRadius: BorderRadius.all(Radius.circular(7)),
                ),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Text.rich(TextSpan(children: [
                      TextSpan(
                        text: '允许通知提醒',
                        style: TextStyle(
                          color: Global.fontColor,
                          fontSize: 15,
                        ),
                      ),
                      TextSpan(
                        text: '（将在开始日期前一天下午六点提醒）',
                        style: TextStyle(
                          color: Global.fontSecondColor,
                          fontSize: 10,
                        ),
                      ),
                    ])),
                    CupertinoSwitch(
                      value: _lights,
                      onChanged: (bool value) {
                        setState(() {
                          _lights = value;
                          _giftManager.currentGift['notification'] = value;
                        });
                      },
                    ),
                  ],
                ),
              ),
              SizedBox(height: 15),
              FormText(
                maxLine: 4,
                text: _giftManager.currentGift['remark'],
                hintText: '备注（选填）',
                onChanged: (text) {
                  _giftManager.currentGift['remark'] = text;
                },
              ),
              SizedBox(height: 10),
              formTitle(
                title: '礼品',
                smTitle: '共${_giftManager.currentGift['gifts'].length}项',
              ),
              buildGiftList(_giftManager.currentGift['gifts']),
              SizedBox(height: 10),
              Container(
                child: Center(
                  child: IconButton(
                    icon: Icon(
                      Icons.add_circle,
                      size: 45,
                    ),
                    tooltip: '保存',
                    onPressed: () {
                      setState(() {
                        _giftManager.currentGift['gifts'].add({
                          'gift_name': '',
                          'recipient': '',
                          'completed': false,
                        });
                      });
                    },
                  ),
                ),
              )
            ],
          ),
        ),
      ),
    );
  }
}

Widget formTitle({String title, String smTitle = ''}) {
  return Container(
    padding: EdgeInsets.fromLTRB(7, 20, 10, 7),
    child: Text.rich(
      TextSpan(
        children: [
          TextSpan(
            text: title,
            style: TextStyle(
              color: Global.fontColor,
              fontSize: 16,
              fontWeight: FontWeight.w600,
            ),
          ),
          TextSpan(
            text: '  $smTitle',
            style: TextStyle(
              color: Global.fontColor,
              fontSize: 11,
              fontWeight: FontWeight.w500,
            ),
          ),
        ],
      ),
    ),
  );
}
